# utf-8 -*- coding: utf-8 -*-
import logging
from config_loader import load_config
from flask_cors import CORS
from flask import Flask, request
from cron_task.push_plus_cron_task import task_alarms_purchase_push_plus_v2
from cron_task.sever_chan_cron_task import alarms_task_today_server_chan_v2, alarms_task_status_reset
from cron_task.wool_task import wool_task
from service.handler import mysql_db, create_alarm, update_alarm_detail, update_alarm_card_detail, query_alarms_list, \
    handle_alarm_item_delete
from service.qx_wechat import qx_wechat_message
from service.club_wechat import wechat_club_message
from apscheduler.schedulers.background import BackgroundScheduler
import asyncio
import multiprocessing

# 青龙面板配置
cfg = load_config("config.yml")
address = cfg["QINGLONG_ADDRESS"]
client_id = cfg["QINGLONG_CLIENT_ID"]
client_secret = cfg["QINGLONG_CLIENT_SECRET"]

# 设置日志级别为 INFO
logging.basicConfig(level=logging.INFO)

application = Flask(__name__)
CORS(application, resources=r'/*')


# 路由Ping
@application.route('/bot/ping', methods=['GET'])
def ping():
    print("Hello, Welcome to my Workspace!")
    return 'Hello, Welcome to my Workspace!'


# 随机获取一个代理IP
@application.route('/bot/random/ip', methods=['GET'])
def get_random_ip():
    conn = mysql_db()
    cur = conn.cursor()
    cur.execute("SELECT ip FROM proxies ORDER BY RAND() LIMIT 1")
    result = cur.fetchone()[0]
    if result is None:
        return 'No data'
    else:
        return result


# 微信公众号消息推送
@application.route('/bot/weixin', methods=['GET', 'POST'])
def weixin_club_route():
    return wechat_club_message()


# 千寻微信框架消息推送
@application.route('/bot/qianxun', methods=['POST'])
def qx_wechat_route():
    return qx_wechat_message()


# 新闹钟创建
@application.route('/bot/alarm/create', methods=['POST'])
def alarm_create_route():
    return create_alarm()


# 更新今日打卡闹钟状态【未做-->已做】
@application.route('/bot/alarm/update', methods=['POST'])
def alarm_update_route():
    # 从请求中获取参数
    data = request.get_json()
    # 更新数据库
    return update_alarm_detail(data)


@application.route('/bot/alarm/card/update', methods=['POST'])
def alarm_card_update_route():
    # 从请求中获取参数
    data = request.get_json()
    # 更新数据库
    return update_alarm_card_detail(data)


# 打卡列表【1打卡列表 2抢购列表】
@application.route('/bot/alarm/list', methods=['GET'])
def alarm_list_route():
    alarm_kind = request.args.get('kind', default=1, type=int)
    return query_alarms_list(alarm_kind)


# 仪表盘
@application.route('/bot/alarm/dashboard', methods=['GET'])
def form():
    return application.send_static_file('alarm.html')


# 删除闹钟数据
@application.route('/bot/alarm/delete', methods=['POST'])
def alarm_list_delete_route():
    # 从请求中获取参数
    data = request.get_json()
    # 更新数据库
    return handle_alarm_item_delete(data)


def run_flask():
    # application.run(host='0.0.0.0', port=7125)
    application.run(host='0.0.0.0', port=7125, use_reloader=False)


def run_asyncio_task(task):
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    loop.run_until_complete(task())
    loop.close()


def run_task(coroutine, *args, **kwargs):
    def task():
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        try:
            loop.run_until_complete(coroutine(*args, **kwargs))
        finally:
            loop.close()

    return task


def setup_schedule():
    scheduler = BackgroundScheduler(daemon=True)
    # 每天零点执行, 打卡状态重置
    scheduler.add_job(alarms_task_status_reset, 'cron', hour=0)
    # 抢购定时任务,1分钟1次【push plus推送】
    scheduler.add_job(task_alarms_purchase_push_plus_v2, 'interval', minutes=1)
    # 今日打卡任务提醒【server酱推送】
    scheduler.add_job(alarms_task_today_server_chan_v2, 'cron', hour=5, minute=30)
    scheduler.add_job(alarms_task_today_server_chan_v2, 'cron', hour=19, minute=0)
    scheduler.add_job(alarms_task_today_server_chan_v2, 'cron', hour=22, minute=30)
    # 线报监控
    scheduler.add_job(wool_task, 'interval', seconds=15)
    scheduler.start()

setup_schedule()

if __name__ == '__main__':
    # 启动 Flask 应用的进程
    flask_process = multiprocessing.Process(target=run_flask)
    flask_process.start()

    # 等待 Flask 进程结束
    flask_process.join()
